package com.quasar.hpatient.module.mine_case_edit;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.ImageView;

import com.quasar.hpatient.R;
import com.quasar.hpatient.api.HttpClient;
import com.quasar.hpatient.api.HttpParams;
import com.quasar.hpatient.bean.comm_album.AlbumPhotoBean;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import lib.quasar.base.frame.BasePresenter;
import lib.quasar.base.frame.OnModelAcceptChangeListener;
import lib.quasar.compress.CompressManager;
import lib.quasar.compress.OnCompressChangeListener;
import lib.quasar.context.BaseApp;
import lib.quasar.context.BaseConstant;
import lib.quasar.recycler.BaseCommonAdapter;
import lib.quasar.recycler.decoration.SpaceDecoration;
import lib.quasar.recycler.holder.RecyclerHolder;
import lib.quasar.recycler.manager.CrashLinearLayoutManager;
import lib.quasar.util.CardUtil;
import lib.quasar.util.DimenUtil;
import lib.quasar.util.ImageUtil;
import lib.quasar.util.InputUtil;
import lib.quasar.util.LogUtil;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * description: 我 ==> 添加病例
 * created by kalu on 2018/7/17 18:44
 */
public final class MineCaseEditPresenter implements BasePresenter {

    private final ArrayList<AlbumPhotoBean> mDatas = new ArrayList<>();

    final void initList(final MineCaseEditView view, final RecyclerView recycler) {

        if (null == recycler || null == view)
            return;

        final AlbumPhotoBean add = new AlbumPhotoBean();
        add.setPicture(String.valueOf(R.drawable.ic_album_add));
        mDatas.add(add);

        final BaseCommonAdapter<AlbumPhotoBean> adapter = new BaseCommonAdapter<AlbumPhotoBean>(mDatas, R.layout.activity_mine_case_edit_type_picture) {

            @Override
            protected void onNext(RecyclerHolder holder, final AlbumPhotoBean model, final int position) {

                final ImageView image = holder.getView(R.id.mine_case_add_picture);

                if (model.isAdd()) {
                    view.setImage(image, R.drawable.ic_album_add);
                } else {
                    view.setImage(image, model.getUrlLittle());
                }

                image.setOnClickListener(v -> {
                    if (model.isAdd()) {
                        view.showAlbum(mDatas);
                    } else {
                        if (TextUtils.isEmpty(model.getPicture())) return;
                        final LinkedList<ImageView> list1 = new LinkedList<>();
                        for (int i = 0; i < mDatas.size(); i++) {
                            list1.add(image);
                        }
                        view.showPhoto(position, mDatas, mDatas, list1);
                    }
                });
            }
        };

        final CrashLinearLayoutManager manager = new CrashLinearLayoutManager(BaseApp.getContext());
        final SpaceDecoration decoration = new SpaceDecoration(DimenUtil.dp2px(10), Color.TRANSPARENT);
        manager.setOrientation(RecyclerView.HORIZONTAL);
        view.setRecycler(recycler, adapter, manager, decoration);
    }

    final void refreshPicture(final MineCaseEditView view, final RecyclerView recycler, final List<String> list) {

        if (null == recycler || null == view || null == list || list.isEmpty())
            return;

        for (String temp : list) {
            final AlbumPhotoBean news = new AlbumPhotoBean();
            news.setPicture(temp);
            news.setCheck(false);
            mDatas.add(0, news);
        }

        refreshPhoto(view, recycler);
    }

    final void pushCase(final MineCaseEditView view, final EditText edit, final int caseId,
                        final String caseTitle, final String hospitalName, final String caseDate, final String caseInspection) {

        InputUtil.closeKeybord(edit);
        final HashMap<String, Object> map = new HashMap<>();
        map.put(HttpParams.ID, caseId);
        map.put(HttpParams.EDITOR_TYPE, 2);
        map.put(HttpParams.HOSPITAL_NAME, hospitalName);
        map.put(HttpParams.MEDICAL_HISTORY_DATE, getDate(caseDate));
        map.put(HttpParams.MEDICAL_TITLE, caseTitle);
        map.put(HttpParams.JSON_CONTENT, caseInspection);

        final ArrayList<String> list = new ArrayList<>();
        for (AlbumPhotoBean temp : mDatas) {
            if (temp.isAdd()) continue;
            list.add(temp.getPicture());
        }
        map.put(HttpParams.JSON_PIC, list);

        final RequestBody params = createParams(map, HttpParams.DATA_TYPE_1_18);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().uploadData(params);

        request(observable, new OnModelAcceptChangeListener<Object>() {
            @Override
            public void modelSucc(Object result) {
                view.toast("保存病例成功");
                view.callBack(list);
            }

            @Override
            public void modelFail() {
                view.toast("保存病例失败");
            }
        });
    }

    @SuppressLint("CheckResult")
    final void compressPhoto(final MineCaseEditView view, RecyclerView recycler, ArrayList<AlbumPhotoBean> list, int position) {

        Observable.create((ObservableOnSubscribe<ArrayList<AlbumPhotoBean>>) e -> {
            final ArrayList<AlbumPhotoBean> temp = new ArrayList<>();
            // 压缩, 保存图片
            for (int i = 0; i < list.size(); i++) {
                final AlbumPhotoBean image = list.get(i);
                String path = image.getPicture();
                String name = path.substring(path.lastIndexOf(File.separatorChar), path.length());
                final int width = image.getWidth();
                final int height = image.getHeight();
                final long size = image.getSize();
                // 获取bitmap
                if (!image.needCompress()) {
                    final AlbumPhotoBean news = new AlbumPhotoBean();
                    news.setPicture(path);
                    news.setCheck(image.isCheck());
                    news.setWidth(width);
                    news.setHeight(height);
                    news.setSize(size);
                    temp.clear();
                    temp.add(news);
                    e.onNext(temp);

                } else {

                    final Bitmap bitmap = ImageUtil.compressImageJava(path, image.calcuWidth(), image.calcuHeight());
                    final String floder = CardUtil.getSDCardPath() + BaseConstant.CACHE_COMPRESS;

                    // 压缩图片
                    CompressManager.syncCompress(true, image.getRatio(), floder, name, bitmap, new OnCompressChangeListener() {
                        @Override
                        public void onCompressStart() {
                        }

                        @Override
                        public void onCompressFinish(String filePath) {

                            if (null != bitmap) {
                                bitmap.recycle();
                            }

                            final AlbumPhotoBean news = new AlbumPhotoBean();
                            news.setPicture(filePath);
                            news.setCheck(image.isCheck());
                            news.setWidth(width);
                            news.setHeight(height);
                            news.setSize(size);

                            temp.clear();
                            temp.add(news);
                            e.onNext(temp);
                        }

                        @Override
                        public void onCompressError(int errorNum, String description) {

                            if (null != bitmap) {
                                bitmap.recycle();
                            }
                        }
                    });
                }
            }
        }).subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(temp -> {
                            uploadPhoto(view, recycler, temp, -1);
                            //  ToastUtil.showToast("分线程: 压缩图片结束");
                        }, throwable -> {
                            // ToastUtil.showToast("分线程: 压缩图片失败");
                            LogUtil.e("", throwable.getMessage(), throwable);
                        },
                        () -> {
                            // ToastUtil.showToast("分线程: 压缩图片结束");
                        },
                        disposable -> {
                            // ToastUtil.showToast("分线程: 开始压缩图片");
                        });
    }

    final void uploadPhoto(final MineCaseEditView view, RecyclerView recycler, ArrayList<AlbumPhotoBean> list, int position) {

        if (null == view || null == recycler) return;

        AlbumPhotoBean old = null;
        if (position != -1) {
            old = mDatas.get(position);
            mDatas.remove(position);
        }

        final HashMap<String, RequestBody> map = new HashMap<>();

        for (int i = 0; i < list.size(); i++) {
            AlbumPhotoBean album = list.get(i);
            final String imagePath = album.getPicture();
            final File file = new File(imagePath);
            final RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            map.put("file" + i + "\"; filename=\"" + file.getName() + "\"", body);

            HashMap<String, Object> params2 = new HashMap<>();
            params2.put(HttpParams.INSPECTIONDATE, getDate());
            final RequestBody params = createParams(params2, HttpParams.DATA_TYPE_412);
            final Observable observable = HttpClient.getSingleHolder().getHttpService().uploadPhoto(params, map);

            AlbumPhotoBean finalOld = old;
            request(observable, new OnModelAcceptChangeListener<List<AlbumPhotoBean>>() {
                @Override
                public void modelFail() {
                    if (null != finalOld) {
                        mDatas.add(position, finalOld);
                    }
                }

                @Override
                public void modelSucc(List<AlbumPhotoBean> model) {

                    if (position == -1) {
                        mDatas.addAll(mDatas.size() - 1, model);
                    } else {
                        mDatas.addAll(position, model);
                    }
                    refreshPhoto(view, recycler);
                }
            });
        }
    }

    private final void refreshPhoto(MineCaseEditView view, RecyclerView recycler) {

        if (null == view || null == recycler) return;

        final RecyclerView.Adapter adapter1 = recycler.getAdapter();
        adapter1.notifyDataSetChanged();
        recycler.smoothScrollToPosition(adapter1.getItemCount() - 1);
    }

    @Override
    public void recycler() {
    }
}
